<?php
// +----------------------------------------------------------------------
// | Options服务服务层
// +----------------------------------------------------------------------
// | 主要服务于Options数据处理
// +----------------------------------------------------------------------
// | 错误编码头 214xxx
// +----------------------------------------------------------------------
namespace common\service;

use common\model\OptionsModel;
use support\ErrorCode;
use support\SingletonTrait;

class OptionsService
{
    // 合同业务模式
    const BUSINESS_MODE_BOTH_SIDES = 'both_sides_mode'; // 双方模式
    const BUSINESS_MODE_TRIPARTITE = 'tripartite_mode'; // 三方模式

    // 单例工具
    use SingletonTrait;

    /**
     * 获取指定Options设置
     * @param $optionName
     * @param array $default
     * @return mixed
     * @throws \Exception
     */
    public function getOptionsData($optionName, $default = [])
    {
        $optionsModel = model(OptionsModel::class);
        $options = [
            'fields' => "config",
            'filter' => ['name' => $optionName]
        ];
        $resData = $optionsModel->findData($options);
        return array_key_exists("config", $resData) ? $resData['config'] : $default;
    }

    /**
     * 获取系统模式配置
     * @param bool $isPageAuth
     * @return array
     */
    public function getSystemModeConfig($isPageAuth = true)
    {
        $defaultModeConfig = $this->getOptionsData("default_mode");
        if (empty($defaultModeConfig)) {
            $defaultModeConfig = [
                "mode" => "strack",
                "open_create_project" => "1",
                "visit_system_admin" => "1",
                "open_clone_project" => "0",
                "open_register" => "0",
                "default_role" => "0",
                "default_clone_project" => "0",
                "default_project_public" => "yes"
            ];
        }

        if ($isPageAuth) {
            $pageAuth = [
                'add_project' => 'yes',
                'visit_system_admin' => 'yes',
            ];
            if ($defaultModeConfig["open_register"] == 1 && $defaultModeConfig["open_create_project"] == 0) {
                $pageAuth["add_project"] = 'no';
            }
            if ($defaultModeConfig["open_register"] == 1 && $defaultModeConfig["visit_system_admin"] == 0) {
                $pageAuth["visit_system_admin"] = 'no';
            }

            return $pageAuth;
        } else {
            return $defaultModeConfig;
        }
    }

    /**
     * 获取指定Options设置项值
     * @param $optionName
     * @param $itemName
     * @return string
     */
    public function getOptionsConfigItemData($optionName, $itemName, $default = '')
    {
        $configData = $this->getOptionsData($optionName);
        if (!empty($configData) && array_key_exists($itemName, $configData)) {
            return $configData["$itemName"];
        } else {
            return $default;
        }
    }

    /**
     * 通用更新修改Options
     * @param $optionName
     * @param $data
     * @param string $message
     * @return array
     */
    public function updateOptionsData($params, $message = '')
    {
        $optionsModel = model(OptionsModel::class);
        $updateOptionResult = $optionsModel->updateOptionsData($params);
        if ($updateOptionResult) {
            if (empty($message)) {
                $message = 'Modify options success';
            }
            // 返回成功数据
            return success_response($message, $updateOptionResult);
        } else {
            // 添加更新系统配置失败错误码 001
            throw_strack_exception($optionsModel->getError(), ErrorCode::SYSTEM_CONFIG_UPDATE_FAILED);
        }
    }

    /**
     * 通用添加配置
     * @param $optionName
     * @param $data
     * @param string $message
     * @return array
     */
    public function addOptionsData($params, $message = '')
    {
        $optionsModel = model(OptionsModel::class);
        $findOptionsResult = $optionsModel->findData(["filter" => ["name" => $params['options_name']]]);

        if (empty($findOptionsResult)) {
            $addOptionsResult = $optionsModel->updateOptionsData($params);
            if ($addOptionsResult) {
                if (empty($message)) {
                    $message = $optionsModel->getSuccessMessage();
                }
                // 返回成功数据
                return success_response($message, $addOptionsResult);
            }

        } else {
            return $this->updateOptionsData($params);
        }
    }

    /**
     * 获取媒体指定上传服务器配置信息
     * @return array
     */
    public function getMediaUploadServer()
    {
        $optionsData = $this->getOptionsData('media_service');

        $mediaServerParam = [];
        if (!empty($optionsData)) {
            $token = md5($optionsData["access_key"] . $optionsData["secret_key"]);

            $mediaServerParam = [
                'name' => 'media_service',
                'request_url' => $optionsData['request_url'],
                'upload_url' => $optionsData['upload_url'],
                'token' => $token
            ];
        }

        return $mediaServerParam;
    }

    /**
     * 获取日志服务器配置信息
     * @return array
     */
    public function getEventLogServer()
    {
        $optionsData = $this->getOptionsData('log_service');

        $mediaServerParam = [];
        if (!empty($optionsData)) {
            $token = md5($optionsData["access_key"] . $optionsData["secret_key"]);

            $mediaServerParam = [
                'name' => 'log_service',
                'access_key' => $optionsData['access_key'],
                'secret_key' => $optionsData['secret_key'],
                'request_url' => $optionsData['request_url'],
                'websocket_url' => $optionsData['websocket_url'],
                'token' => $token
            ];
        }

        return $mediaServerParam;
    }

    /**
     * 获取合同业务模式配置
     * @return mixed
     */
    public function getBusinessMode()
    {
        $platformTenantSettings = $this->getOptionsData("platform_tenant_settings");

        if (empty($platformTenantSettings['business_mode'])) {
            return [];
        }
        return $platformTenantSettings['business_mode'];
    }

    /**
     * 服务列表接口
     * @return array
     * @throws \Exception
     */
    public function getServiceList()
    {
        $default = [
            'teamones-oauth', 'teamones-saas', 'teamones-im',
            'teamones-script', 'teamones-doc', 'teamones-assets', 'teamones-review', 'teamones-work-hour',
            'teamones-app-shop', 'teamones-media', 'teamones-log', 'teamones-dcc'
        ];
        $platformTenantSettings = $this->getOptionsConfigItemData("default_settings", "platform_service_list", implode(',', $default));
        return explode(',', $platformTenantSettings);
    }
}
